#!/bin/bash

message() {
  echo "CutBox Setup: ${1}"
}

EXISTS_FAILED=""
EXISTS_CHECK=0

exists_check() {
  cross_mark="✗"
  check_mark="✓"

  if [ $# -ne 1 ]; then
    message "exists_check: No arguments provided"
    exit 1
  else
    if [ -x  $1 ]; then
      printf "${check_mark}"
    else
      printf "${cross_mark}"
      EXISTS_CHECK=1
      EXISTS_FAILED="${EXISTS_FAILED} ${1}"
    fi
  fi
}

WHICH_FAILED=""
WHICH_CHECK=0

which_check() {
  cross_mark="✗"
  check_mark="✓"

  if [ $# -ne 1 ]; then
    message "which_check: No arguments provided"
    exit 1
  else
    if [ -x "$(which $1)" ]; then
      printf "${check_mark}"
    else
      printf "${cross_mark}"
      WHICH_CHECK=1
      WHICH_FAILED="${WHICH_FAILED} ${1}"
    fi
  fi
}

NPM_FAILED=""
NPM_CHECK=0

npm_check() {
  cross_mark="✗"
  check_mark="✓"

  if [ $# -ne 1 ]; then
    message "npm_check: No arguments provided"
    exit 1
  else
    if [ -x "$(npm exec which $1)" ]; then
      printf "${check_mark}"
    else
      printf "${cross_mark}"
      NPM_CHECK=1
      NPM_FAILED="${NPM_FAILED} ${1}"
    fi
  fi
}

if [ -x "$(which brew)" ]; then
  message "Running brew installs, npm install and pip install -r requirements.txt"

  brew install coreutils
  brew install node
  brew install ripgrep
  brew install cmark
  brew install cocoapods
  brew install carthage
  brew install llvm

  npm install
  pip install -r requirements.txt
else
  message "Homebrew must be installed and working."
  exit 1
fi
PROJECT_DIR=$(git rev-parse --show-toplevel)
cat <<EOF
PLEASE NOTE: CutBox expects:

Build/Test & release tooling...

- [$(which_check brew)] homebrew (in case anything is missing)
- [$(which_check pod)] cocoapods
- [$(which_check xcpretty)] xcpretty
- [$(which_check jv)] jv (json validator)
- [$(exists_check /usr/local/opt/llvm/bin/llvm-cov)] llvm-cov /usr/local/opt/llvm/bin/llvm-cov

For release...

- [$(which_check cmark)] cmark
- [$(which_check npm)] npm
- [$(npm_check appdmg)] appdmg
- [$(npm_check semver)] semver

anything missing? (Get help at https://gitter.im/CutBox/Lobby)

=========================================================================================="
Install Pods
EOF

pushd $PROJECT_DIR/CutBox || exit 1

pod install

popd ||  exit 1

echo "To build run: bin/build"

if [[ $WHICH_CHECK == 1 || $NPM_CHECK == 1 || $EXISTS_CHECK == 1 ]]; then
  echo "Something missing? Setup cannot find:
${WHICH_FAILED}
${NPM_FAILED}."
  exit 1
fi

exit 0
